{% extends "admin/base.html" %}

{% block title %}文章管理{% endblock %}

{% block page_title %}文章管理{% endblock %}

{% block extra_css %}{% endblock %}

{% block content %}
<div class="bg-white rounded-xl shadow-sm overflow-hidden">
    <!-- 页面头部 -->
    <div class="px-8 py-6 border-b border-gray-200 flex justify-between items-center flex-wrap gap-4">
        <h1 class="m-0 text-slate-700 text-xl font-semibold flex items-center gap-2">
            <i class="fas fa-file-alt"></i> 文章管理
        </h1>
        <div class="flex gap-4 items-center">
            <a href="/admin/posts/new" class="bg-blue-500 text-white px-4 py-2 rounded-md no-underline font-medium text-sm transition-all duration-300 inline-flex items-center gap-2 hover:bg-blue-600 hover:text-white hover:no-underline">
                <i class="fas fa-plus"></i>
                写新文章
            </a>
        </div>
    </div>
    
    <!-- 筛选和搜索区域 -->
    <div class="px-8 py-6 bg-gray-50 border-b border-gray-200 flex gap-4 items-center flex-wrap">
        <div class="flex flex-col gap-2">
            <label for="status-filter" class="text-sm font-medium text-gray-600">状态筛选</label>
            <select id="status-filter" class="px-3 py-2 border border-gray-300 rounded-md text-sm min-w-36 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <option value="">全部状态</option>
                <option value="published">已发布</option>
                <option value="draft">草稿</option>
                <option value="archived">已归档</option>
            </select>
        </div>
        
        <div class="flex flex-col gap-2">
            <label for="category-filter" class="text-sm font-medium text-gray-600">分类筛选</label>
            <select id="category-filter" class="px-3 py-2 border border-gray-300 rounded-md text-sm min-w-36 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <option value="">全部分类</option>
                {% for category in categories %}
                <option value="{{ category.id }}">{{ category.name }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div class="flex flex-col gap-2">
            <label for="search-input" class="text-sm font-medium text-gray-600">搜索文章</label>
            <input type="text" id="search-input" placeholder="输入标题或内容关键词..." class="px-3 py-2 border border-gray-300 rounded-md text-sm min-w-48 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
        </div>
        
        <button class="bg-blue-500 text-white border-0 px-4 py-2 rounded-md cursor-pointer text-sm transition-colors duration-300 self-end inline-flex items-center gap-2 hover:bg-blue-600" onclick="applyFilters()">
            <i class="fas fa-search"></i>
            搜索
        </button>
        
        <button class="bg-gray-500 text-white border-0 px-4 py-2 rounded-md cursor-pointer text-sm transition-colors duration-300 self-end inline-flex items-center gap-2 hover:bg-gray-600" onclick="resetFilters()">
            <i class="fas fa-undo"></i>
            重置
        </button>
    </div>
    
    <!-- 文章列表 -->
    <div class="overflow-x-auto">
        <table class="w-full border-collapse">
            <thead>
                <tr class="bg-gray-50">
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-2/5">文章信息</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/6">分类</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/6">状态</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/6">统计</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/8">发布时间</th>
                    <th class="px-4 py-4 text-left font-semibold text-gray-600 border-b-2 border-gray-200 text-sm w-1/8">操作</th>
                </tr>
            </thead>
            <tbody id="posts-tbody">
                <!-- 动态加载的文章列表 -->
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <div class="mt-0">
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between">
                <!-- 分页信息 -->
                <div class="text-sm text-gray-600" id="pagination-info">
                    加载中...
                </div>
                
                <!-- 分页导航 -->
                <nav class="flex items-center space-x-1" id="pagination-nav">
                    <!-- 动态生成分页 -->
                </nav>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 文章管理相关功能
let currentPage = 1;
let totalPages = 1;
let currentFilters = {
    status: '',
    category: '',
    search: ''
};

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadPosts();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 搜索按钮
    document.querySelector('button[onclick="applyFilters()"]').addEventListener('click', applyFilters);
    
    // 重置按钮
    document.querySelector('button[onclick="resetFilters()"]').addEventListener('click', resetFilters);
    
    // 回车键搜索
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            applyFilters();
        }
    });
}

// 加载文章列表
async function loadPosts(page = 1) {
    try {
        const params = new URLSearchParams({
            page: page,
            ...currentFilters
        });
        
        const response = await fetch(`/api/posts?${params.toString()}`);
        const data = await response.json();
        
        if (data.success) {
            renderPosts(data.data.posts);
            renderPagination(data.data.pagination);
            currentPage = page;
        } else {
            Utils.notification.show(data.message || '加载文章失败', 'error');
        }
    } catch (error) {
        console.error('加载文章失败:', error);
        Utils.notification.show('加载文章失败，请稍后重试', 'error');
    }
}

// 渲染文章列表
function renderPosts(posts) {
    const tbody = document.getElementById('posts-tbody');
    
    if (posts.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-12 text-gray-500">
                    <i class="fas fa-file-alt text-4xl mb-2"></i>
                    <h3 class="text-lg font-medium text-slate-700 mb-1">暂无文章</h3>
                    <p class="m-0">开始创建你的第一篇文章吧！</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = posts.map(post => `
        <tr class="hover:bg-gray-50">
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <div class="flex items-center gap-4">
                    <div class="w-16 h-10 rounded-md bg-gray-100 flex items-center justify-center text-gray-500 text-xs">
                        ${post.cover_image ? 
                            `<img src="${post.cover_image}" alt="封面" class="w-full h-full object-cover rounded-md">` : 
                            '<i class="fas fa-image"></i>'
                        }
                    </div>
                    <div class="flex-1">
                        <h3 class="m-0 mb-1 text-base font-semibold text-slate-700">${escapeHtml(post.title)}</h3>
                        <p class="m-0 text-sm text-gray-600 leading-relaxed">${escapeHtml(post.excerpt || (post.content.length > 100 ? post.content.substring(0, 100) + '...' : post.content))}</p>
                        <div class="text-xs text-gray-500 mt-1">
                            作者: ${escapeHtml(post.author.name || post.author.username)} | 
                            创建: ${formatDate(post.created_at)}
                        </div>
                    </div>
                </div>
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                ${post.category ? 
                    `<span class="font-medium" style="color: ${post.category.color};">${escapeHtml(post.category.name)}</span>` : 
                    '<span class="text-gray-500">未分类</span>'
                }
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <span class="px-2 py-1 rounded text-xs font-medium ${getStatusClass(post.status)}">
                    ${getStatusText(post.status)}
                </span>
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <div class="flex items-center gap-2 text-xs text-gray-600 whitespace-nowrap">
                    <div class="flex items-center gap-1">
                        <i class="fas fa-eye"></i> ${post.view_count || 0}
                    </div>
                    <div class="flex items-center gap-1">
                        <i class="fas fa-heart"></i> ${post.like_count || 0}
                    </div>
                    <div class="flex items-center gap-1">
                        <i class="fas fa-comment"></i> ${post.comment_count || 0}
                    </div>
                </div>
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                ${post.published_at ? 
                    `<div class="text-sm text-gray-600">${formatDate(post.published_at)}</div>` : 
                    '<span class="text-gray-500 text-sm">未发布</span>'
                }
            </td>
            <td class="px-4 py-4 border-b border-gray-100 align-middle">
                <div class="flex gap-2">
                    <a href="/admin/posts/${post.id}/edit" class="bg-blue-500 text-white px-3 py-1.5 rounded cursor-pointer transition-all duration-200 text-sm no-underline inline-flex items-center justify-center hover:bg-blue-600" title="编辑">
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="${post.html_path || '/post/' + post.id}" class="bg-green-500 text-white px-3 py-1.5 rounded cursor-pointer transition-all duration-200 text-sm no-underline inline-flex items-center justify-center hover:bg-green-600" title="查看" target="_blank">
                        <i class="fas fa-external-link-alt"></i>
                    </a>
                    <button class="bg-red-500 text-white px-3 py-1.5 rounded cursor-pointer transition-all duration-200 text-sm inline-flex items-center justify-center hover:bg-red-600" onclick="deletePost(${post.id})" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        </tr>
    `).join('');
}

// 渲染分页
function renderPagination(pagination) {
    const info = document.getElementById('pagination-info');
    const nav = document.getElementById('pagination-nav');
    
    // 更新分页信息
    const start = (pagination.page - 1) * pagination.per_page + 1;
    const end = Math.min(pagination.page * pagination.per_page, pagination.total);
    info.textContent = `显示第 ${start} - ${end} 条，共 ${pagination.total} 条记录`;
    
    // 清空导航
    nav.innerHTML = '';
    
    // 创建按钮的辅助函数
    const mkBtn = (html, disabled, onClick) => {
        const el = document.createElement(disabled ? 'span' : 'button');
        el.className = disabled ? 'px-3 py-2 text-gray-300 cursor-not-allowed' : 'px-3 py-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
        el.innerHTML = html;
        if (!disabled && onClick) el.addEventListener('click', onClick);
        return el;
    };
    
    // 首页
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-left"></i>', pagination.page === 1, () => loadPosts(1)));
    
    // 上一页
    nav.appendChild(mkBtn('<i class="fas fa-chevron-left"></i>', !pagination.has_prev, () => loadPosts(pagination.page - 1)));
    
    // 页码 - 显示所有页码，与其他页面保持一致
    for (let p = 1; p <= pagination.pages; p++) {
        if (p === pagination.page) {
            const span = document.createElement('span');
            span.className = 'px-3 py-2 bg-blue-600 text-white rounded-lg font-medium';
            span.textContent = String(p);
            nav.appendChild(span);
        } else {
            const button = document.createElement('button');
            button.className = 'px-3 py-2 text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
            button.textContent = String(p);
            button.addEventListener('click', () => loadPosts(p));
            nav.appendChild(button);
        }
    }
    
    // 下一页
    nav.appendChild(mkBtn('<i class="fas fa-chevron-right"></i>', !pagination.has_next, () => loadPosts(pagination.page + 1)));
    
    // 末页
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-right"></i>', pagination.page === pagination.pages, () => loadPosts(pagination.pages)));
}

// 应用筛选条件
function applyFilters() {
    currentFilters.status = document.getElementById('status-filter').value;
    currentFilters.category = document.getElementById('category-filter').value;
    currentFilters.search = document.getElementById('search-input').value;
    
    loadPosts(1);
}

// 重置筛选条件
function resetFilters() {
    document.getElementById('status-filter').value = '';
    document.getElementById('category-filter').value = '';
    document.getElementById('search-input').value = '';
    
    currentFilters.status = '';
    currentFilters.category = '';
    currentFilters.search = '';
    
    loadPosts(1);
}

// 删除文章
async function deletePost(postId) {
    Utils.confirm.show('确定要删除这篇文章吗？此操作不可恢复！', async function() {
        try {
            const response = await fetch(`/api/posts/${postId}`, {
                method: 'DELETE'
            });
            const data = await response.json();
            
            if (data.success) {
                Utils.notification.show('文章删除成功', 'success');
                loadPosts(currentPage);
            } else {
                Utils.notification.show(data.message || '删除失败', 'error');
            }
        } catch (error) {
            console.error('删除失败:', error);
            Utils.notification.show('删除失败，请稍后重试', 'error');
        }
    });
}

// 工具函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function getStatusClass(status) {
    switch (status) {
        case 'published': return 'bg-green-100 text-green-600';
        case 'draft': return 'bg-yellow-100 text-yellow-600';
        case 'archived': return 'bg-gray-100 text-gray-600';
        default: return 'bg-gray-100 text-gray-600';
    }
}

function getStatusText(status) {
    switch (status) {
        case 'published': return '已发布';
        case 'draft': return '草稿';
        case 'archived': return '已归档';
        default: return '未知';
    }
}
</script>
{% endblock %}